from django.db import transaction
from rest_framework import serializers
from goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SpecificationOption, SKUSpecification


class SKUSpecSerializer(serializers.Serializer):
   spec_id = serializers.IntegerField()
   option_id = serializers.IntegerField()

class SKUTableSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    category = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()

    specs = SKUSpecSerializer(read_only=True, many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    @transaction.atomic
    def create(self, validated_data):
        sid = transaction.savepoint()
        try:
            sku = SKU.objects.create(**validated_data)
            specs = self.context["request"].data["specs"]

            for spec_dict in specs:
                SKUSpecification.objects.create(sku=sku, spec_id=spec_dict["spec_id"], option_id=spec_dict["option_id"])

        except Exception:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("创建sku,或者规格失败")

        else:
            transaction.savepoint_commit(sid)
            return sku

    @transaction.atomic
    def update(self, instance, validated_data):
        sid = transaction.savepoint()
        try:
            SKU.objects.filter(id=instance.id).update(**validated_data)
            specs = self.context["request"].data["specs"]
            for spec_dict in specs:
                SKUSpecification.objects.filter(sku_id=instance.id, spec_id=spec_dict["spec_id"]).update(option_id=spec_dict["option_id"])

        except Exception:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("创建sku,或者规格失败")

        else:
            transaction.savepoint_commit(sid)
            return SKU.objects.get(id=instance.id)

class SKUCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ("id", "name")

class GoodSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ('id', 'name')

class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ('id', "value")


class SPUSpecsSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    options = SpecificationOptionSerializer(read_only=True, many=True)

    class Meta:
        model = SPUSpecification
        fields = '__all__'


